package com.esionet.service.impl;

import com.esionet.common.enumresource.StatusEnum;
import com.esionet.common.utils.bean.R;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.esionet.common.enumresource.WhetherEnum;
import com.esionet.common.exception.MyException;
import com.esionet.common.utils.StringUtil;
import com.esionet.common.utils.constants.Constant;
import com.esionet.dao.SysUserDao;
import com.esionet.entity.SysRole;
import com.esionet.entity.SysUser;
import com.esionet.service.SysRoleService;
import com.esionet.service.SysUserRoleService;
import com.esionet.service.SysUserService;

import java.util.*;


/**
 * 系统用户
 *
 * @author chenyi
 * @email 228112142@qq.com
 * @date 2016年9月18日 上午9:46:09
 */
@Service("sysUserService")
public class SysUserServiceImpl implements SysUserService {
    @Autowired
    private SysUserDao sysUserDao;
    @Autowired
    private SysUserRoleService sysUserRoleService;
    @Autowired
    private SysRoleService sysRoleService;

    //12小时后过期
    private final static int EXPIRE = 3600 * 12;

    @Override
    public List<String> queryAllPerms(String userId) {
        return sysUserDao.queryAllPerms(userId);
    }

    @Override
    public List<String> queryAllMenuId(String userId,String module) {
        return sysUserDao.queryAllMenuId(userId,module);
    }

    @Override
    public SysUser queryByUserName(String username) {
        return sysUserDao.queryByUserName(username);
    }

    @Override
    public SysUser get(String userId) {
        return sysUserDao.get(userId);
    }

    @Override
    public List<SysUser> getList(Map<String, Object> map) {
        return sysUserDao.getList(map);
    }

    @Override
    public int getCount(Map<String, Object> map) {
        return sysUserDao.getCount(map);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void save(SysUser user) {
        user.setCreateTime(new Date());
        user.setPassword(new Sha256Hash(Constant.INIT_PASSWORD).toHex());
        //检查角色是否越权
//        this.checkRole(user);

        user.setRoleId(StringUtils.join(user.getRoleIds(),","));
        sysUserDao.save(user);
        //保存用户与角色关系

        sysUserRoleService.saveOrUpdate(user.getUserId(), user.getRoleIds());

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(SysUser user) {
        if (StringUtils.isBlank(user.getPassword())) {
            user.setPassword(null);
        } else {
            user.setPassword(new Sha256Hash(user.getPassword()).toHex());
        }

        //检查角色是否越权
//        this.checkRole(user);

        user.setRoleId(StringUtils.join(user.getRoleIds(),","));

        sysUserDao.update(user);
        //保存用户与角色关系

        sysUserRoleService.saveOrUpdate(user.getUserId(), user.getRoleIds());


    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteBatch(String[] userIds) {
        for (String userId:userIds) {
            SysUser user = sysUserDao.get(userId);
            if(WhetherEnum.YES.getValue().equals(user.getIsSys())){
                throw new MyException("删除失败!存在系统内置用户");
            }
        }
        sysUserDao.deleteBatch(userIds);
    }

    @Override
    public int updatePassword(String userId, String password, String newPassword) {
        Map<String, Object> map = new HashMap<>();
        map.put("userId", userId);
        map.put("password", password);
        map.put("newPassword", newPassword);
        return sysUserDao.updatePassword(map);
    }

    @Override
    public void initPassword(String[] userIds) {
        for (String userId:userIds) {
            SysUser user = sysUserDao.get(userId);
            if(WhetherEnum.YES.getValue().equals(user.getIsSys())){
                throw new MyException("重置密码失败!存在系统内置用户");
            }
        }
        for (String userId : userIds) {
            SysUser user = new SysUser();
            user.setUserId(userId);
            user.setPassword(new Sha256Hash(Constant.INIT_PASSWORD).toHex());
            sysUserDao.update(user);
        }
    }

    @Override
    public SysUser getInfo(String userId) {
        SysUser user = sysUserDao.getInfo(userId);
        String roleId = user.getRoleId();
        StringBuilder sb = new StringBuilder();
        if (!StringUtil.isEmpty(roleId)) {
            String[] roleIds = roleId.split(",");
            for (String id : roleIds) {
                SysRole role = sysRoleService.get(id);
                if (role != null) {
                    sb.append(role.getRoleName()).append(" ");
                }
            }
        }
        user.setRoleId(sb.toString());
        return user;
    }


    /**
     * 检查角色是否越权
     */
    private void checkRole(SysUser user) {
        //如果不是超级管理员，则需要判断用户的角色是否自己创建
        if (Constant.SUPER_ADMIN.equals(user.getCreateUserId())) {
            return;
        }

        //查询用户创建的角色列表
        List<String> roleIdList = sysRoleService.queryRoleIdList(user.getCreateUserId());
        List<String> roleIds = new ArrayList<>(Arrays.asList(user.getRoleIds()));
        //判断是否越权
        if (!roleIdList.containsAll(roleIds)) {
            throw new MyException("新增用户所选角色，不是本人创建");
        }
    }


    @Override
    public void updateStatus(String[] ids, String stateValue) {
        for (String id : ids) {
            SysUser sysUser = new SysUser();
            sysUser.setUserId(id);
            sysUser.setStatus(stateValue);
            sysUserDao.update(sysUser);
        }
    }

    @Override
    public void updateMyInfo(SysUser user) {
        sysUserDao.update(user);
    }

    @Override
    public SysUser findByToken(String token) {
        return sysUserDao.findByToken(token);
    }

    @Override
    public R login(String username, String password) {
        //查询用户信息
        SysUser user = sysUserDao.queryByUserName(username);

        //账号不存在
        if(user == null) {
            return R.error("账号或密码不正确");
        }
        password = new Sha256Hash(password).toHex();
        //密码错误
        if(!password.equals(user.getPassword())) {
            return R.error("账号或密码不正确");
        }

        //账号锁定
        if(!StatusEnum.ENABLE.getValue().equals(user.getStatus()) ){
            return R.error("账号已被冻结,请联系管理员");
        }
        //生成一个token
        String token = UUID.randomUUID().toString();
        //过期时间 12小时
        Date expireTime = new Date(System.currentTimeMillis() + EXPIRE * 1000);

        user.setToken(token);
        user.setExpireTime(expireTime);
        //更新token
        sysUserDao.update(user);

        return R.ok("登录成功").put("token",token);
    }

}
